In this article I will show you how to make a json file from c# object using asp.net mvc. When user click the button event, the jQuery ajax call the server side mvc action method CreateJson(). The function contains JavascriptSerializer, it convert data to json format and save json to file of the project folder.
Here, I created a folder and named as json, make sure create it your project and also import System.Web.Script.Serialization to it.
Step 1: Create an asp.net mvc project and right click on the controller folder and create a new controller and name it as HomeController. Inside the HomeController copy and paste the following code.
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult CreateJson()
{
try
{
using (models context = new models())
{
context.Configuration.ProxyCreationEnabled = false; // included the following code
var CustomerList =context.Customers.ToList();
var jsondata = new JavaScriptSerializer().Serialize(CustomerList);
string path =Server.MapPath("~/Json/");
System.IO.File.WriteAllText(path + "customer.json",jsondata);
return Json(CustomerList, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ez)
{
return null;
}
}
Step 2: Right click on the Share folder and create a razor view named as index. Copy and paste the following code.
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<p>
<input type="button" id="btnCreateJson" value="Create Json" class="btn btn-default" />
</p>
<script type="text/javascript">
$(function () {
$("#btnCreateJson").click(function () {
$.post("/Home/CreateJson", function (response) {
if (response != null) {
alert("Json Created");
location.reload();
}
else {
alert("Error");
}
});
})
});
</script>
Create Json file c#:
Post your comments / questions
Recent Article
- FieldError: Cannot resolve keyword 'id' into field in Django project
- How to hide the ID field from the Django admin?
- It is impossible to add a non nullable field without specifying a default. Django error
- ImportError: cannot import name 'url' from 'django.conf.urls' - Django Error
- How to Enable Virtualization in BIOS Security Settings in Intel Processors For Android Studio?
- Dependency 'androidx.activity:activity:1.8.0' requires libraries and applications that depend on it.
- AttributeError: 'NoneType' object has no attribute 'get_text' - Python
- ModuleNotFoundError: No module named 'openpyxl' - Python
Related Article